"use strict";

const resetContent = `
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    list-style: none;
    text-decoration: none;
    width:100%;
    height:100%;
}
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}
`;
const head = document.getElementsByTagName("head")[0];

function setRemUnit(grid) {
  // console.log(" - ", grid);
  const docEl = document.documentElement;
  const g = grid || 750;
  var rem = docEl.clientWidth / g;
  docEl.style.fontSize = rem + "px";
  console.log("setRemUnit ---", docEl.clientWidth, " - ", rem, " - ", g);
}

function updateViewPort(content) {
  const me = document.querySelector("meta[name='viewport']");
  console.log(`updateViewPort`, me);

  if (!me || me.content.indexOf("width=device-width") < 0) {
    const am = document.createElement("meta");
    am.name = "viewport";
    am.content = content || "width=device-width, initial-scale=1.0";
    head.appendChild(am);
    console.log(am.content);
  }
}
export default {
  inited: false,
  init(options) {
    const styleName = "reset";
    const { grid, viewport } = options || {
      grid: 750,
      viewport: "width=device-width, initial-scale=1.0",
    };
    if (document.getElementsByName(styleName).length == 0) {
      var resetStyle = document.createElement("style");
      resetStyle.name = styleName;
      resetStyle.innerHTML = resetContent;
      head.appendChild(resetStyle);
    }

    //// console.log(document.documentElement.clientWidth);
    // console.log(document.documentElement.clientWidth);
    //

    const dpr = window.devicePixelRatio || 1;
    // console.log(dpr);

    function setBodyFontSize() {
      if (document.body) {
        document.body.style.fontSize = 12 * dpr + "px";
      } else {
        document.addEventListener("DOMContentLoaded", setBodyFontSize);
      }
    }
    setBodyFontSize();

    setRemUnit(grid);
    updateViewPort(viewport);
    // reset rem unit on page resize
    window.addEventListener("resize", function () {
      setRemUnit();
    });
    window.addEventListener("pageshow", function (e) {
      if (e.persisted) {
        setRemUnit();
      }
    });
    this.inited = true;
  },
  set grid(val) {
    console.log(`this.inited ${this.inited} --  grid ${val}`);
    if (this.inited) {
      setRemUnit(val);
      return;
    }
    this.init({ grid: val });
  },
  set viewport(val) {
    if (this.inited) {
      updateViewPort(val);
      return;
    }
    this.init({ viewport: val });
  },
};
